package com.example.hao.ximalaya.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;

import com.example.hao.ximalaya.application.MyApp;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class HttpUtils {

    private static final String TAG = "Hao";

    /**
     * 喜马拉雅推荐数据的网址
     */
    public static final String URL_RECOMMEND = "http://mobile.ximalaya.com/discovery-firstpage/v2/explore/ts-1535959506994?appid=0&categoryId=-2&device=android&deviceId=57cf4217-4dcc-364b-9845-40eaa02775bc&includeActivity=true&includeSpecial=true&inreview=false&network=wifi&operator=2&pullToRefresh=false&scale=1&version=6.5.16";

    public static String get(String address) {
        HttpURLConnection conn = null;
        BufferedReader br = null;
        try {
            URL url = new URL(address);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String s = br.readLine();
                Log.d(TAG, "get: " + s);
                return s;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

    public interface OnOkCallBack {
        void onFailure(@NonNull IOException e);

        void onResponse(@NonNull String jsonStr);
    }

    private static final Handler HANDLER = new Handler();

    //okHttp get 请求 异步
    public static void okHttpGetAsync(@NonNull String url, @NonNull final OnOkCallBack onOkCallBack) {

        Request request = new Request.Builder().url(url).get().build();
        Log.d(TAG, "okHttpGetAsync: request" + request);
        Call call = MyApp.getOkHttpClient().newCall(request);
        Log.d(TAG, "okHttpGetAsync: call" + call);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull final IOException e) {
                Log.e(TAG, "onFailure: " + "请求失败" + e.getMessage());
                HANDLER.post(new Runnable() {
                    @Override
                    public void run() {
                        onOkCallBack.onFailure(e);
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull final Response response) {
                try {
                    ResponseBody body = response.body();
                    if (body != null) {
                        final String string = body.string();
                        HANDLER.post(new Runnable() {
                            @Override
                            public void run() {

                                onOkCallBack.onResponse(string);

                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    //okHttp get 请求 同步
    public static String okHttpGetSync(String address) {
//        Log.w(TAG, "OkHttpGet: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        try {
            OkHttpClient client = MyApp.getOkHttpClient();
//            Log.d(TAG, "OkHttpGet:client >>>"+client );
            Request build = new Request.Builder().url(address).get().build();
//            Log.d(TAG, "OkHttpGet:build >>>"+build );
            Call call = client.newCall(build);
            Log.d(TAG, "OkHttpGet: call>>>" + call);
            Response execute = call.execute();
            Log.d(TAG, "OkHttpGet:execute >>> " + execute);
            ResponseBody body = execute.body();
            Log.d(TAG, "OkHttpGet:body>>> " + body);
            if (body != null) {
                String string = body.string();
                Log.d(TAG, "OkHttpGet:string >>>" + string);
                return string;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public interface onAcceptCallBack  {
        void onAccept(String s);

        void onAccept(Throwable throwable);
    }


    //RxJava RxAndroid 观察者模式 链式调用. okHttp get请求 同步
    public static void method1(@NonNull final String url, @NonNull final onAcceptCallBack back) {

        Disposable subscribe = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) {
                String s = okHttpGetSync(url);
                emitter.onNext(s);
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        back.onAccept(s);

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        back.onAccept(throwable);

                    }
                });
    }

    public static void method2(@NonNull final String url, @NonNull final OnOkCallBack onOkCallBack){
        Disposable subscribe = Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) {
                okHttpGetAsync(url,onOkCallBack);
            }
        }).subscribe();


    }

}
